package com.keepers.repair.service;

import android.annotation.TargetApi;
import android.app.job.JobInfo;
import android.app.job.JobScheduler;
import android.content.ComponentName;
import android.content.Context;
import android.os.Build;

import com.blankj.utilcode.util.Utils;

/**
 * JobScheduler管理类，单例模式
 * 执行系统任务
 * <p>
 * http://blog.csdn.net/andrexpert
 */

public class JobSchedulerManager {
    private static final int JOB_ID = 1;
    private static JobSchedulerManager mJobManager;
    private        JobScheduler        mJobScheduler;
    private        boolean             isStarter;

    private JobSchedulerManager() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mJobScheduler = (JobScheduler) Utils.getApp().getSystemService(Context.JOB_SCHEDULER_SERVICE);
        }
    }

    public static JobSchedulerManager getJobSchedulerInstance() {
        if (mJobManager == null) {
            mJobManager = new JobSchedulerManager();
        }
        return mJobManager;
    }

    @TargetApi(21)
    public void startJobScheduler() {
        // 如果JobService已经启动或API<21，返回
        if (isStarter || isBelowLOLLIPOP()) {
            return;
        }
        mJobScheduler.cancel(JOB_ID);
        JobInfo.Builder builder = new JobInfo.Builder(JOB_ID, new ComponentName(Utils.getApp(), AliveJobService.class));
        if (Build.VERSION.SDK_INT >= 24) {
            builder.setMinimumLatency(JobInfo.DEFAULT_INITIAL_BACKOFF_MILLIS); //执行的最小延迟时间
            builder.setOverrideDeadline(JobInfo.DEFAULT_INITIAL_BACKOFF_MILLIS);  //执行的最长延时时间
            builder.setMinimumLatency(JobInfo.DEFAULT_INITIAL_BACKOFF_MILLIS);
            builder.setBackoffCriteria(JobInfo.DEFAULT_INITIAL_BACKOFF_MILLIS, JobInfo.BACKOFF_POLICY_LINEAR);//线性重试方案
        } else {
            builder.setPeriodic(JobInfo.DEFAULT_INITIAL_BACKOFF_MILLIS);
        }
        // 设置设备重启时，执行该任务
        builder.setPersisted(true);  // 设置设备重启时，执行该任务
        builder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY);
        builder.setRequiresCharging(true); // 当插入充电器，执行该任务
        JobInfo info = builder.build();
        isStarter = true;
        mJobScheduler.schedule(info); //开始定时执行该系统任务
    }

    @TargetApi(21)
    public void stopJobScheduler() {
        if (isBelowLOLLIPOP())
            return;
        mJobScheduler.cancelAll();
    }

    private boolean isBelowLOLLIPOP() {
        // API< 21
        return Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP;
    }
}
